<template>
  <div style="height: 100vh; display: flex; align-items: center; justify-content: center; background-color: #0f9fff">
    <div style="display: flex; background-color: white; width: 50%; border-radius: 5px; overflow: hidden">
      <div style="flex: 1">
        <img src="@/assets/login.png" alt="" style="width: 100% ;height: 100%">
      </div>
      <div style="flex: 1; display: flex; align-items: center; justify-content: center; flex-direction: column;">
        <el-form :model="user" style="width: 80%" :rules="rules" ref="loginRef">
          <div style="font-size: 20px; font-weight: bold; text-align: center; margin-bottom: 20px">欢迎登录校园招聘系统</div>
          <el-form-item prop="username">
            <el-input prefix-icon="el-icon-user" size="medium" placeholder="请输入用户名" v-model="user.username"></el-input>
          </el-form-item>
          <el-form-item prop="password1">
            <el-input prefix-icon="el-icon-lock" size="medium" show-password placeholder="请输入密码" v-model="user.password1"></el-input>
          </el-form-item>
          <el-form-item style="display: flex; justify-content: center; width: 100%;">
            <el-button type="primary" style="width: 44%;" @click="login">登录</el-button>
            <el-button type="primary" style="width: 44%;" @click="dialogFormVisible = true">注册</el-button>
          </el-form-item>
          <div style="margin-top: 10px; text-align: center;">
            <a href="/login" style="font-size: 12px;">忘记密码？</a>
          </div>
        </el-form>
      </div>

    </div>
    <div>
      <el-dialog title="提示" :visible.sync="dialogFormVisible" width="35%" center>
        <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
          <el-form-item label="用户名" prop="username">
            <el-input type="text" v-model="ruleForm.username" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="pass">
            <el-input type="password" v-model="ruleForm.password" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="checkPass">
            <el-input type="password" v-model="user.checkPass" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item prop="email" label="邮箱">
            <el-input v-model="ruleForm.email"></el-input>
          </el-form-item>
          <el-form-item label="身份">
            <el-select v-model="ruleForm.role" placeholder="请选择注册身份">
              <el-option label="学生" value="student"></el-option>
              <el-option label="公司" value="company"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
    <el-button @click="dialogFormVisible = false">取 消</el-button>
    <el-button type="primary" @click="dialogFormVisible = false; submitForm('ruleForm');" >确 定</el-button>
  </span>
      </el-dialog>
    </div>
  </div>
</template>


<script>

import axios from "axios";

export default {
  name: "Login",
  data() {

    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        if (this.user.checkPass !== '') {
          this.$refs.ruleForm.validateField('checkPass');
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      value = this.user.checkPass;
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.ruleForm.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      dialogFormVisible: false,
      userinfo:[],
      user: {
        username: '',
        password1: '',
        checkPass: '',
      },
      searchuser: {
        username: '',
        email:'',
      },
      registerSta:false,
      ruleForm: {
        user_id:'',
        username:'',
        password: '',
        email:'',
        role:'',
        company_name:'企业',
        name:'学生',
        experience:'无',
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
        ],
        password1: [
          { required: true, message: '请输入密码', trigger: 'blur' },
        ],
        password: [
          { required: true,validator: validatePass, trigger: 'blur' }
        ],
        checkPass: [
          {required: true, validator: validatePass2, trigger: 'blur' }
        ],
        email:[
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ]
      }
    }
  },
  created() {

  },
  methods: {
    submitForm(formName) {
      axios.get('http://localhost:8080/User/selectAll', this.searchuser).then(response => {
        this.searchuser = response.data.data;
        if(this.registerSta===true){
          this.userinfo=response.data.data;
          for (let user of this.userinfo) {
            if (user.username === this.ruleForm.company_name||user.username === this.ruleForm.name) {
              this.ruleForm.user_id=user.user_id;
            }
          }
          if(this.ruleForm.role === 'student'){
            this.addStu();
          }else if(this.ruleForm.role === 'company'){
            this.addBoss();
          }
        }
        if(this.registerSta===false) {
          let userExists = false;
          for (let user of this.searchuser) {
            if (user.username === this.ruleForm.username) {
              userExists = true;
              break;
            }
            if (user.email === this.ruleForm.email) {
              userExists = true;
              break;
            }
          }
          if (!userExists) {
            this.$refs[formName].validate((valid) => {
              if (valid) {
                this.register();
                this.registerSta=true;
              } else {
                console.log('error submit!!');
                this.dialogFormVisible = true;
                return false;
              }
            });
          } else {
            console.log('error submit!!');
            this.$message.error("注册失败，用户已存在");
          }
        }

      })
          .catch(error => {
            console.error('Error fetching users:', error);
            this.$message.error("获取用户信息失败");
          });

    },

    register(){
        // 实现新增功能的逻辑
        axios.post('http://localhost:8080/User/add',this.ruleForm)
            .then(response => {
              // 处理新增成功逻辑
              if(this.ruleForm.role === 'student'){
                this.ruleForm.name=this.ruleForm.username;
              }else if(this.ruleForm.role === 'company'){
                this.ruleForm.company_name=this.ruleForm.username;
              }
              this.submitForm()
              this.$message.success("新增成功");
              this.dialogVisible = false;
            })
            .catch(error => {
              // 处理新增失败逻辑
              console.error('Error adding new item:', error);
              this.$message.error("新增失败");
            });
    },
    login() {
      this.$refs['loginRef'].validate((valid) => {
        if (valid) {
          // 验证通过
          axios.post('http://localhost:8080/loginController/login', this.user)
              .then(response => {
                if(response.data.code==200) {
                  localStorage.setItem('userData', JSON.stringify(response.data.data));
                  if(response.data.data.role==="admin"){
                    this.$message.success("登录成功");
                    this.$router.push("/admin");
                  }
                  if(response.data.data.role==="student"){
                    this.$message.success("登录成功");
                    this.$router.push("/Student");
                  }
                  if(response.data.data.role==="company"){
                    this.$message.success("登录成功");
                    this.$router.push("/Boss");
                  }
                }
                else {
                  this.$message.error("登录失败");
                }
              })
              .catch(error => {
                console.error('Error adding new item:', error);
                this.$message.error("登录失败");
              });
        }
      })
    },
    addStu(){

      axios.post('http://localhost:8080/User/addStu',this.ruleForm).then(response => {
        this.dialogVisible = false;
        this.registerSta=false;
      })
          .catch(error => {
            console.error('Error fetching users:', error);
          });
    },
    addBoss(){
      axios.post('http://localhost:8080/User/addBoss',this.ruleForm).then(response => {
        this.dialogVisible = false;
        this.registerSta=false;
      })
          .catch(error => {
            console.error('Error fetching users:', error);
          });
    }
  }
}
</script>

<style scoped>

</style>